﻿@using System.Net.Http.Headers
@using Tool.Models
@using Tool.Services
@using Tool.Utils
@inject ISnackbar snackbar
@inject IDialogService dialogService
@inject EvdService evdService
@inject IJSRuntime JavaScript;
@inject ISnackbar Snackbar
<MudGrid>
    <MudItem xs="4">
        <MudTextField @bind-Value="UserCode" Label="报销单号" Variant="Variant.Text" Adornment="Adornment.Start"
                      AdornmentIcon="@Icons.Material.Filled.LockPerson" Clearable="true" />
    </MudItem>

    <MudItem xs="4" Class="align-content-center">
        <MudButton Class="align-self-center" FullWidth="true" Disabled="@_processing" OnClick="GetPushLogs" Variant="Variant.Filled" Color="Color.Primary">
            @if (_processing)
            {
                <MudProgressCircular Class="ms-n1" Indeterminate="true" />
                <MudText Class="ms-2">Processing</MudText>
            }
            else
            {
                <MudText>获取推送指令信息</MudText>
            }
        </MudButton>
    </MudItem>

    

    <MudItem xs="4" Class="align-content-center">
        <MudButton Class="align-self-center" FullWidth="true" OnClick="ClearResults" Variant="Variant.Filled" Color="Color.Primary">
            <MudText>清空</MudText>
        </MudButton>
    </MudItem>

    <MudItem xs="12">
        <MudTable Items="@_evds" @bind-SelectedItems="_selectedEvds" Dense="true" Hover="true" Bordered="true" Striped="true" MultiSelection="true" CustomHeader="true" CustomFooter="true">
            <ToolBarContent>
                <MudText Typo="Typo.h6">指令推送记录</MudText>
                <MudText Typo="Typo.h6">(总数：@_totalCount)</MudText>
                <MudSpacer />
            </ToolBarContent>
            <HeaderContent>
                <MudTHeadRow Checkable="true">
                    <MudTh>Id</MudTh>
                    <MudTh>Operation</MudTh>
                    <MudTh>MsgId</MudTh>
                    <MudTh>AdvCode</MudTh>
                    <MudTh>AgencyCode</MudTh>
                    <MudTh>UserCode</MudTh>
                    <MudTh>AgencyName</MudTh>
                    <MudTh>ReimburseNo</MudTh>
                    <MudTh>FileType</MudTh>
                    <MudTh>FilePath</MudTh>
                    <MudTh>SendUrl</MudTh>
                    <MudTh>SendStatus</MudTh>
                    <MudTh>SendTime</MudTh>
                    <MudTh>SendErrorMessage</MudTh>
                    <MudTh>IntranetStatus</MudTh>
                    <MudTh>IntranetTime</MudTh>
                    <MudTh>IntranetErrorMessage</MudTh>
                    <MudTh>StorageStatus</MudTh>
                    <MudTh>StorageTime</MudTh>
                    <MudTh>StorageErrorMessage</MudTh>
                    <MudTh>CreateTime</MudTh>
                    <MudTh>Action</MudTh>
                </MudTHeadRow>
            </HeaderContent>
            <RowTemplate>
                <MudTd DataLabel="Id">@context.Id</MudTd>
                <MudTd DataLabel="Topic">@context.Topic</MudTd>
                <MudTd DataLabel="MsgId">@context.MsgId</MudTd>
                <MudTd DataLabel="AdvCode">@context.AdvCode</MudTd>
                <MudTd DataLabel="AgencyCode">@context.AgencyCode</MudTd>
                <MudTd DataLabel="UserCode">@context.UserCode</MudTd>
                <MudTd DataLabel="AgencyName">@context.AgencyName</MudTd>
                <MudTd DataLabel="ReimburseNo">@context.ReimburseNo</MudTd>
                <MudTd DataLabel="FileType">@context.FileType</MudTd>
                <MudTd DataLabel="FilePath">@context.FilePath</MudTd>
                <MudTd DataLabel="SendUrl">@context.SendUrl</MudTd>
                <MudTd DataLabel="SendStatus">@context.SendStatus</MudTd>
                <MudTd DataLabel="SendTime">@context.SendTime</MudTd>
                <MudTd DataLabel="SendErrorMessage">@context.SendErrorMessage</MudTd>
                <MudTd DataLabel="IntranetStatus">@context.IntranetStatus</MudTd>
                <MudTd DataLabel="IntranetTime">@context.IntranetTime</MudTd>
                <MudTd DataLabel="IntranetErrorMessage">@context.IntranetErrorMessage</MudTd>
                <MudTd DataLabel="StorageStatus">@context.StorageStatus</MudTd>
                <MudTd DataLabel="StorageTime">@context.StorageTime</MudTd>
                <MudTd DataLabel="StorageErrorMessage">@context.StorageErrorMessage</MudTd>
                <MudTd DataLabel="CreateTime">@context.CreateTime</MudTd>
                <MudTd DataLabel="Action"><MudButton OnClick="() => ShowEvd(context.FilePath)" Variant="Variant.Filled" Color="Color.Info">查看</MudButton></MudTd>
            </RowTemplate>
            <FooterContent>
                <MudTFootRow Checkable="true">
                    <MudTd colspan="5">Selected: @_selectedEvds?.Count</MudTd>
                </MudTFootRow>
            </FooterContent>
            <PagerContent>
                <MudTablePager />
            </PagerContent>
        </MudTable>
    </MudItem>
</MudGrid>
@code {
    [Parameter]
    public string UserCode { get; set; }
    [Parameter]
    public string GroupName { get; set; }
    [Parameter]
    public string SelectedSite { get; set; }
    [Parameter]
    public HttpResponseHeaders ResponseHeaders { get; set; }

    private bool _processing = false;
    private bool _downloadingEvd = false;
    private bool _downloadingPay = false;
    private List<PushLogDto> _evds = new List<PushLogDto>();
    private HashSet<PushLogDto> _selectedEvds = new HashSet<PushLogDto>();
    private int _totalCount = 0;

    private async Task GetPushLogs()
    {
        _processing = true;
        try
        {
            var sql = $"";
            _evds = await evdService.GetPushLogs(sql, SelectedSite, ResponseHeaders, string.Empty);
            await GetPushLogsCount();
        }
        catch (Exception ex)
        {
            snackbar.Add(ex.Message, Severity.Error);
        }
        finally
        {
            _processing = false;
        }
    }


    private async Task GetPushLogsCount()
    {
        _processing = true;
        try
        {
            var sql = $"select count(1) from push_command_log where command_content like '%{UserCode}%'";
            _totalCount = await evdService.GetPushLogsCount(sql, SelectedSite, ResponseHeaders, string.Empty);
        }
        catch (Exception ex)
        {
            snackbar.Add(ex.Message, Severity.Error);
        }
        finally
        {
            _processing = false;
        }
    }

    private async Task ShowEvd(string evdUrl)
    {
        var options = new DialogOptions
        {
            FullWidth = true,
            MaxWidth = MaxWidth.Medium,
            CloseOnEscapeKey = true
            // FullScreen = true
        };
        await dialogService.ShowAsync<ShowEvdDetails>("查看EVD", new DialogParameters { { "EvdUrl", evdUrl }, { "SelectedSite", SelectedSite }, { "GroupName", GroupName } }, options);
    }

    private async Task DownloadEvds()
    {
        _downloadingEvd = true;
        try
        {
            foreach (var item in _selectedEvds)
            {
                await DownloadFile(item.FilePath, item.ReimburseNo, "evd");
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"下载文件异常：{ex.Message}", Severity.Error);
        }
        finally
        {
            _downloadingEvd = false;
        }
    }

    private async Task DownloadPayFiles()
    {
        _downloadingPay = true;
        try
        {
            foreach (var item in _selectedEvds)
            {
                await DownloadFile(item.FilePath, item.ReimburseNo, "pay");
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"下载文件异常：{ex.Message}", Severity.Error);
        }
        finally
        {
            _downloadingPay = false;
        }
    }

    private async Task DownloadFile(string fileUrl, string reimNo, string extension)
    {
        bool isStartWithHttp = fileUrl.StartsWith("http");
        // 下载文件
        // 1. 提取 fileId (去掉第一个 '/' 之前的部分)
        string fileId = string.Empty;
        if (isStartWithHttp)
        {
            fileId = fileUrl.Substring(fileUrl.IndexOf("/group") + 1);
        }
        else
        {
            fileId = fileUrl.Substring(fileUrl.IndexOf("/") + 1);
        }


        // 2. 获取当前时间戳 (秒)
        int ts = (int)(DateTimeOffset.UtcNow.ToUnixTimeSeconds());

        // 3. 生成 token
        string token = FileHelper.GetToken(fileId, ts, "SFqdFASTDFS#@!$%^");

        // 4. 构造带参数的 URL
        string queryString = $"token={token}&ts={ts}";
        string fullFileUrl = $"{fileUrl}?{queryString}";

        // 5. 构造完整的下载 URL
        // 注意：原始 Java 代码中 URL 后面有空格，这里已修正
        string completeUrl = string.Empty;
        if (!isStartWithHttp)
        {
            completeUrl = $"{FileHelper.GetFileHost(SelectedSite, GroupName)}/{fullFileUrl}";
        }
        else
        {
            completeUrl = fullFileUrl;
        }

        byte[] bytes = await HttpUtil.DownloadBytesAsync(completeUrl);

        await JavaScript.InvokeVoidAsync("downloadFileFromBytes", bytes, $"{reimNo}.{extension}", "application/zip");
    }
    private void ClearResults()
    {
        _evds.Clear();
        _selectedEvds.Clear();
        _totalCount = 0;
    }
}
